<?php

namespace backend\modules\supplier\controllers\goods;

use Yii;
use yii\helpers\ArrayHelper;
use backend\modules\supplier\models\form\GoodsForm;
use common\models\goods\Goods;
use \common\models\product\Product;
use common\models\goods\GoodsType;
use common\models\goods\GoodsSearch;
use common\models\goods\GoodsCategory;
use common\models\Brand;
use backend\modules\supplier\models\Slot;
use backend\modules\supplier\models\SupplierController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * DefaultController 继承自 Goods 模型。
 */
class DefaultController extends SupplierController {

    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 显示所有 Goods 模型。
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new GoodsSearch();
        
        $params=Yii::$app->request->queryParams;
        $params['GoodsSearch']['supplier_id'] = $this->admin->supplier_id;
        $params['GoodsSearch']['is_del']=0;
        $dataProvider = $searchModel->search($params);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * 显示单个 Goods 模型。
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * 创建一个 Goods 模型。
     * 如果创建成功,浏览器将被重定向到“视图”页。
     * @return mixed
     */
    public function actionCreate() {
        $model = new GoodsForm();
        
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->adminLog($model);
            return $this->redirect(['update', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'admin' => $this->admin,
            ]);
        }
    }

    /**
     * 更新现有的 Goods 模型。
     * 如果更新成功,浏览器将被重定向到“视图”页。
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->adminLog($model);
            return $this->redirect(['update', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'admin' => $this->admin,
            ]);
        }
    }

    /**
     * 删除现有的 Goods 模型。
     * 如果删除成功,浏览器将被重定向到“index”页面。
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $model = Goods::findOne($id);
        if($model){
            $model->is_del=1;
            $model->save();
            $this->adminLog("商品：{$model->name} 删除");
        }
        return $this->redirect(['index']);
    }

    /**
     * 根据主键ID，查找 Goods 模型。
     * 如果模型没有找到，则会抛出一个404异常。
     * @param integer $id
     * @return Goods the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        $goodsForm = new GoodsForm;
        $goodsForm->id = $id;
        $goodsForm->getInfo();
        
        return $goodsForm;
    }

    
    /**
     * AJAX获取类目
     * @return type
     */
    public function actionGetCategory() {
        $post = Yii::$app->request->post();
        $id = intval($post['id']);
        $dropdowns=[];
        
        $category = GoodsCategory::findOne($id);
        if ($category) {
            $parents = $category->getRoute();
            $parents[]=$category;

            foreach ($parents as $item) {
                if($result = ArrayHelper::map(GoodsCategory::getList($item->parent_id), 'id', 'name')){
                    $dropdowns[]=[
                        'id'=>$item->id,
                        'list'=>$result,
                    ];
                }
            }
            
            if($l=ArrayHelper::map(GoodsCategory::getList($category->id), 'id', 'name')){
                $dropdowns[]=[
                    'id'=>0,
                    'list'=>$l,
                ];
            }
            
            
            //获取绑定的品牌
            $brands = null;
            if (!empty($category->brand_ids)) {
                $ids = explode(',', $category->brand_ids);
                $ids && $brands = Brand::findAll($ids);
            }

            return $this->renderAjax('_category', [
                        'dropdowns' => $dropdowns,
                        'brands' => $brands,
            ]);
        }
    }

    /**
     * 查找货位
     * @param type $search
     * @param type $id
     */
    public function actionGetSlot($search = null, $id = null) {
        $out = ['more' => false];
        if (!is_null($search)) {
            $slots = Slot::find()->where(['and', ['supplier_id' => $this->admin->supplier_id], ['like', 'name', $search]])->limit(10)->asArray()->all();

            if ($slots) {
                $result = [];
                foreach ($slots as $item) {
                    $result[] = ['id' => $item['id'], 'text' => $item['name']];
                }
            } else {
                $result = ['id' => 0, 'text' => '没有匹配的货位！'];
            }
            $out['results'] = $result;
        }
        echo \yii\helpers\Json::encode($out);
    }

    /**
     * 获取商品类型列表
     * @param type $typeId 商品类型ID
     * @param type $goods_id 
     */
    public function actionGetType($typeId,$goods_id=0){
        $model=GoodsType::find()->where('enable=1 and id=:id',[':id'=>$typeId])->one();
        if($model){
            return $this->renderPartial('_attr', [
                'goodsType'=> $model,
                'goodsForm' => new GoodsForm,
            ]);
        }
    }
    
    /**
     * 检测货品编号重复
     * @param type $sn
     * @param type $product_id
     * @return type
     */
    public function actionCheckProductSn($sn, $product_id) {
        $pid = intval($product_id);
        
        if(empty($sn)){
            return;
        }
        
        $where = "supplier_id=:supplier_id and sn=:sn";
        $params = [':supplier_id' => $this->admin->supplier_id, ':sn' => $sn];
        if ($pid > 0) {
            $where.=' and id!=:pid';
            $params[':pid'] = $pid;
        }

        $count = Product::find()->where($where, $params)->count();

        return $count > 0 ? $this->renderJSON(['msg' => '该货品编号已被使用，不能重复！'], FALSE) : $this->renderJSON([]);
    }

}
